package com.ybear.mvp.view.bind;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewbinding.ViewBinding;

public class BindHelper<VB extends ViewBinding> {
    private final IViewBindSelf<VB> mViewBindSelf;
    private VB mViewBinding;

    public BindHelper(IViewBindSelf<VB> viewSelf) {
        mViewBindSelf = viewSelf;
    }

    private View bind(Activity activity, @NonNull VB binding) {
        mViewBinding = binding;
        View root = binding.getRoot();
        if( activity != null ) activity.setContentView( root );
        mViewBindSelf.initView( binding );
        return root;
    }

    public View bindView(@Nullable Activity activity,
                         @NonNull LayoutInflater layoutInflater, @Nullable ViewGroup container) {
        VB bind = mViewBindSelf.onBindingView( layoutInflater, container );
        if( bind == null ) return null;
        View root = bind( activity, bind );
        if( activity != null ) mViewBindSelf.setContentView( root );
        return root;
    }

    public VB getViewBinding() { return mViewBinding; }

    public void onDestroyView() { mViewBinding = null; }
}
